import 'package:base_library/base_library.dart';
import 'package:flutter/material.dart';
import 'package:wan_android_flutter/protocol/model.dart';
import 'package:wan_android_flutter/repository/common.dart';
import 'package:wan_android_flutter/ui/pages/home/home.dart';
import 'blocs/application_bloc.dart';
import 'blocs/bloc_provider.dart';
import 'blocs/main_bloc.dart';
import 'common/sp_helper.dart';
import 'package:dio/dio.dart';
import 'package:fluintl/fluintl.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() => runApp(
      MyApp()
    );

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Locale _locale;

//  Color _themeColor = Colours.app_main;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        BaseConstant.routeMain: (ctx) => HomePage(),
      },
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: HomePage(),
      locale: _locale,
//      localizationsDelegates: [
//        GlobalMaterialLocalizations.delegate,
//        GlobalWidgetsLocalizations.delegate,
//        CustomLocalizations.delegate
//      ],
//      supportedLocales: CustomLocalizations.supportedLocales,
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initAsync();
//    _initListener();
  }

  void _initAsync() async {
    await SpUtil.getInstance();
    if (!mounted) return;
    _init();
//    _loadLocale();
  }

  void _initListener() {
    final ApplicationBloc bloc = BlocProvider.of<ApplicationBloc>(context);
    bloc.appEventStream.listen((value) {
      _loadLocale();
    });
  }

  void _loadLocale() {
    setState(() {
      LanguageModel model =
          SpHelper.getObject<LanguageModel>(Constant.keyLanguage);
      if (model != null) {
        _locale = new Locale(model.languageCode, model.countryCode);
      } else {
        _locale = null;
      }

      String _colorKey = SpHelper.getThemeColor();
//      if (themeColorMap[_colorKey] != null)
//        _themeColor = themeColorMap[_colorKey];
    });
  }

  void _init() {
//    DioUtil.openDebug();
    Options options = DioUtil.getDefOptions();
    options.baseUrl = Constant.server_address;
    String cookie = SpUtil.getString(BaseConstant.keyAppToken);
    if (ObjectUtil.isNotEmpty(cookie)) {
      Map<String, dynamic> _headers = new Map();
      _headers["Cookie"] = cookie;
      options.headers = _headers;
    }
    HttpConfig config = new HttpConfig(options: options);
    DioUtil().setConfig(config);
  }

//  void _initListener() {
//    final ApplicationBloc bloc = BlocProvider.of<ApplicationBloc>(context);
//    bloc.appEventStream.listen((value) {
//      _loadLocale();
//    });
//  }

}
